﻿(function ($) {
    var $this, wfcore, divHistory,
        legend = [{color: '#ccff99', descript: '未处理节点'}
            , {color: '#ff9933', descript: '正处理节点'}
            , {color: '#336633', descript: '已处理节点'}
            , {color: '#333', descript: '未处理规则'},
            {color: '#336633', descript: '已处理过规则'}];


    var mathHelper = new MathHelper();

    var cxt, canvas, current, setInterval, isReload = false;
    var submitFlag = 0;
    var condition = [];

    var WorkflowMoinitor = function () {
        var me = this;
        me.Instance = wfcore.Instance || {};
        me.Template = wfcore.Template || {};
        me.templateId = wfcore.templateId;
        me.instanceId = wfcore.instanceId;
        this.proportion = 1.1;
        this.Proportion(this.proportion);
    }

    function glegend(obj) {
        var container = $("<div >");
        container.append($("<div class='color'>").css('background-color', obj.color)).append($("<div>").html(obj.descript));
        return container;
    }


    WorkflowMoinitor.prototype = {
        nextParticipaints: [],
        postActivityCollection: [],

        Proportion: function (proportion) {
            StyleDefine.Activity.Start.Radius *= 2;
            StyleDefine.Activity.End.Radius *= 2;
            StyleDefine.Activity.Branching.diamondWidth *= proportion;
            StyleDefine.Activity.Branching.diamondHeight *= proportion;
            StyleDefine.Activity.Merging.diamondWidth *= proportion;
            StyleDefine.Activity.Merging.diamondHeight *= proportion;
            StyleDefine.Activity.Condition.diamondHeight *= proportion;
            StyleDefine.Activity.Condition.diamondWidth *= proportion;
            StyleDefine.Activity.Approval.activityRectVertexX *= proportion;
            StyleDefine.Activity.Approval.activityRectVertexY *= proportion;
            StyleDefine.Window.width *= proportion;
            StyleDefine.Window.height *= proportion;
            StyleDefine.Activity.Drafting.activityRectVertexX *= proportion;
            StyleDefine.Activity.Drafting.activityRectVertexY *= proportion;
        },

        //初始化表单，设置窗口大小等
        InitialForm: function () {
            $this.html('');
            var me = this;
            me.maxHeigth = 0;
            me.maxWidth = 0;
            me.operate = 3;
            var div = $("<div class='modal fade' id='divHistroyContainer'>\
        <div class='modal-dialog modal-lg'>\
            <div class='modal-content'>\
                <div class='widget'>\
                    <div class='widget-header bg-themeprimary'>\
                        <i class='widget-icon glyphicon glyphicon-time'></i>\
                        <span class='widget-caption'>审批历史</span>\
                        <div class='widget-buttons'>\
                            <a data-dismiss='modal'>\
                                <i class='fa fa-times'></i>\
                            </a>\
                        </div>\
                    </div>\
                    <div class='widget-body'>\
                        <div class='row'>\
                            <div class='col-lg-12' id='divHistory'></div>\
                        </div>\
                    </div>\
                </div>\
            </div>\
        </div>\
    </div>");
            $("body").append(div);
            divHistory = $("#divHistory", div);
            var legendcontainer = $("<div class='legend'>")
            $.each(legend, function (i, val) {
                //最后一个不输出
                if (i < legend.length - 2)
                    legendcontainer.append(glegend(val));
            })
            $this.append(legendcontainer).css('background-image', "url('/Packages/WorkflowManagement/Images/workflow_background.png')");

            me.mathHelper = new MathHelper();
            divPic = $this;
            canvas = me.InitialCanvas();
            cxt = canvas.cxt;
            canvas = canvas.canvas;
        },

        //获取全部有效的工作项
        GenerateEffectWorkItems: function () {

            var me = this;
            me.effectWorkItems = new Array();
            var tmp = -1;
            if (me.Instance.workitems)
                $.each(me.Instance.workitems, function (i, val) {
                    if (val.isDel == 0 && val.handleResult != HandleResult.Retrieve && val.handleResult != HandleResult.Return && val.handleResult != HandleResult.Cancel)
                        me.effectWorkItems[me.effectWorkItems.length] = val;
                })
        },
        //获取全部有效的规则
        GenerateEffectRules: function () {
            var me = this;
            me.effectRules = new Array();
            $.each(me.Template.rules, function (i, val) {
                if (val.isDel == 0 && val.ruleType == 0)
                    me.effectRules[me.effectRules.length] = val;
            })
        },
        //绘制图像
        DrawPic: function (callback) {
            var me = this;
            me.GenerateEffectWorkItems();
            me.GenerateEffectRules();
            me.GetHandledRuleInvoke();
            divPic.unbind();


            if (!wfcore.IsCreate)
                divPic.dblclick(function () {
                    mylayer = me.ShowHistory(me.Instance.workitems);
                })
            $.each(me.Template.activities, function (a, val) {
                me.AddActivity(val);
            });


            $.each(me.effectRules, function (r, val) {
                me.AddRule(val);
            });


            var height = screen.height - 148;
            var width = screen.width - 45;

            me.maxHeigth += 100;
            me.maxWidth += 100;
            me.maxHeigth = me.maxHeigth > height ? me.maxHeigth : height;
            me.maxWidth = me.maxWidth > width ? me.maxWidth : width
            divPic.css('height', me.maxHeigth).css('width', me.maxWidth);
            canvas.attr('height', me.maxHeigth).attr('width', me.maxWidth);
            var p = divPic.parent();

            p.css('width', '100%').css('overflow', 'auto');
            if (me.maxHeigth > height)
                p.css('height', height);


            $.each(me.effectRules, function (r, val) {
                me.DrawRule(val);
            });

            if (condition.length > 0)
                $.each(condition, function (i, val) {
                    me.AddActivity(val);
                })


            if (callback)
                callback();
        },

        InitialCanvas: function () {
            var canvas = $("<canvas>").css({
                'position': 'absolute',
                "z-index": "0",
                'top': '0px',
                "left": "0px"
            }).attr({"width": StyleDefine.Window.width, "height": StyleDefine.Window.height});
            var cxt = canvas[0].getContext("2d");
            divPic.append(canvas);
            return {
                'canvas': canvas,
                'cxt': cxt
            }
        },
        AddActivity: function (activity) {

            var me = this;
            if (activity.isDel == 0) {


                var activity_coordinate = activity.coordinate.split('$');
                var position = new Point(activity_coordinate[0], activity_coordinate[1]);
                position.X *= me.proportion;
                position.Y *= me.proportion;
                activity.Position = position;
                var me = this;
                var result = me.GetActivityStatus(activity.id);
                activity.result = result;

                var background = legend[0].color;
                if (result.status == 1) background = legend[2].color;
                else if (result.status == 0) background = legend[1].color;

                switch (activity.activityType) {
                    case ActivityType.Start:
                        var div = $("<div>").css({
                            "position": "absolute",
                            "top": position.Y - StyleDefine.Activity.Start.Radius,
                            "left": position.X - StyleDefine.Activity.Start.Radius,
                            "width": StyleDefine.Activity.Start.Radius * 2,
                            "height": StyleDefine.Activity.Start.Radius * 2,


                        });
                        div.append($("<img src='/assets/js/workflow/images/start.png'>").css('width', '100%'));

                        divPic.append(div);
                        break;
                    case ActivityType.End:
                        var div = $("<div>").css({
                            "position": "absolute",
                            "top": position.Y - StyleDefine.Activity.Start.Radius,
                            "left": position.X - StyleDefine.Activity.Start.Radius,
                            "width": StyleDefine.Activity.Start.Radius * 2,
                            "height": StyleDefine.Activity.Start.Radius * 2,
                            //"background-image": "url('/Packages/WorkflowManagement/Images/end.png')"
                        });
                        divPic.append(div);
                        div.append($("<img src='/assets/js/workflow/images/end.png'>").css('width', '100%'));
                        break;
                    case ActivityType.Freedom:


                        var url = "/Packages/WorkflowManagement/Images/freedom_uh.png";
                        if (result.status == 0) url = "/Packages/WorkflowManagement/Images/freedom_hing.png";
                        else if (result.status == 1) url = "/Packages/WorkflowManagement/Images/freedom_h.png";


                        var img = $("<img>").attr("src", url).css({
                            "width": StyleDefine.Activity.Start.Radius * 2,
                            "height": StyleDefine.Activity.Start.Radius * 2
                        });
                        var div = $("<div>").css({
                            "position": "absolute",
                            "top": position.Y - StyleDefine.Activity.Start.Radius,
                            "left": position.X - StyleDefine.Activity.Start.Radius,
                            "width": StyleDefine.Activity.Branching.diamondWidth * 2,
                            "height": StyleDefine.Activity.Branching.diamondHeight * 2
                        });
                        div.append(img);
                        divPic.append(div);
                        if (result.status == 0) {
                            me.BindMenu(div, result);
                        }
                        break;

                    case ActivityType.Branching:
                        var url = result.status == 1 ? "/Packages/WorkflowManagement/Images/branching_h.png" : "/Packages/WorkflowManagement/Images/branching_uh.png";
                        var img = $("<img>").attr("src", url).css({
                            "width": StyleDefine.Activity.Branching.diamondWidth * 2,
                            "height": StyleDefine.Activity.Branching.diamondHeight * 2
                        });
                        var div = $("<div>").css({
                            "position": "absolute",
                            "top": position.Y - StyleDefine.Activity.Branching.diamondHeight,
                            "left": position.X - StyleDefine.Activity.Branching.diamondWidth,
                            "width": StyleDefine.Activity.Branching.diamondWidth * 2,
                            "height": StyleDefine.Activity.Branching.diamondHeight * 2
                        });
                        div.append(img);
                        divPic.append(div);
                        break;
                    case ActivityType.Merging:
                        var url = result.status == 1 ? "/Packages/WorkflowManagement/Images/merging_h.png" : "/Packages/WorkflowManagement/Images/merging_uh.png";
                        var img = $("<img>").attr("src", url).css({
                            "width": StyleDefine.Activity.Merging.diamondWidth * 2,
                            "height": StyleDefine.Activity.Merging.diamondHeight * 2
                        });
                        var div = $("<div>").css({
                            "position": "absolute",
                            "top": position.Y - StyleDefine.Activity.Merging.diamondHeight,
                            "left": position.X - StyleDefine.Activity.Merging.diamondWidth,
                            "width": StyleDefine.Activity.Branching.diamondWidth * 2,
                            "height": StyleDefine.Activity.Branching.diamondHeight * 2
                        });
                        div.append(img);
                        divPic.append(div);
                        break;
                    case ActivityType.Condition:
                        if (activity.Init) {

                            cxt.save();
                            cxt.beginPath();
                            cxt.moveTo(position.X - StyleDefine.Activity.Condition.diamondWidth, position.Y);
                            cxt.lineTo(position.X, position.Y - StyleDefine.Activity.Condition.diamondHeight);
                            cxt.lineTo(position.X + StyleDefine.Activity.Condition.diamondWidth, position.Y);
                            cxt.lineTo(position.X, position.Y + StyleDefine.Activity.Condition.diamondHeight);
                            cxt.closePath();
                            cxt.fillStyle = background;
                            cxt.strokeStyle = "#000";
                            cxt.fill();
                            cxt.stroke();
                            cxt.restore();

                            //var url = result.status == 1 ? "url('/Packages/WorkflowManagement/Images/condition_h.png')" : "url('/Packages/WorkflowManagement/Images/condition_uh.png')";
                            var div = $("<div>").css({
                                "position": "absolute",
                                "top": position.Y - StyleDefine.Activity.Condition.diamondHeight,
                                "left": position.X - StyleDefine.Activity.Condition.diamondWidth,
                                "width": StyleDefine.Activity.Condition.diamondWidth * 2,
                                "height": StyleDefine.Activity.Condition.diamondHeight * 2 + 3,
                                "line-height": StyleDefine.Activity.Condition.diamondHeight * 2 + 3 + "px",
                                //"background-image": url,
                                "overflow": "hidden",
                                "text-align": "center",
                                'color': background == legend[0].color ? '#222' : 'white'
                            });
                            //div.append(img);
                            divPic.append(div);

                            div.html(activity.activityName);
                        } else {
                            activity.Init = true;
                            condition.push(activity);
                        }
                        break;
                    default:

                        var div = $("<div>").css({
                            "top": position.Y - StyleDefine.Activity.Approval.activityRectVertexY,
                            "left": position.X - StyleDefine.Activity.Approval.activityRectVertexX,
                            "width": StyleDefine.Activity.Approval.activityRectVertexX * 2,
                            "height": StyleDefine.Activity.Approval.activityRectVertexY * 2,

                            "background-color": background,
                            "border": "1px solid #555",
                            'position': 'absolute',
                            "box-shadow": "#777 0px 0px 3px 3px",

                            'border-radius': '5px',
                            'color': background == legend[0].color ? '#222' : 'white'
                        });

                        var divac = $("<div class='divDescription'>").css({
                            "width": '100%',
                            "height": StyleDefine.Activity.Approval.activityRectVertexY - 7,
                            "line-height": '18px',
                            'font-size': '16px'

                        }).html(activity.activityName).attr("title", activity.activityName);

                        if (result.status == 0 || (wfcore.IsCreate && activity.activityType == ActivityType.Drafting)) {
                            current = div;
                        }

                        div.append(divac);
                        if (me.operate > 0) {
                            if (result.status >= 0) {
                                var content = me.GetHandler(result.workItem);
                                var divha = $("<div class='divDescription'>").css({
                                    "width": StyleDefine.Activity.Approval.activityRectVertexX * 2 - 4,
                                    "height": StyleDefine.Activity.Approval.activityRectVertexY - 4
                                }).html(content.handlers).attr("title", content.title);
                                div.append(divha);
                                //任务调整
                            }
                        }

                        if (activity.activityType != ActivityType.Branching && activity.activityType != ActivityType.Merging && activity.activityType != ActivityType.Condition)
                            if (!wfcore.IsCreate) div.dblclick(function (e) {
                                var item = new Array();
                                $.each(me.Instance.workitems, function (l, hitem) {
                                    if (hitem.activityId.toUpperCase() == activity.activityId.toUpperCase())
                                        item[item.length] = hitem;
                                });
                                me.ShowHistory(item);
                                e.stopPropagation();
                            });

                        divPic.append(div);
                        break;
                }
            }

        },
        ReLoad: function () {
            var me = this;
            me.templateId = wfcore.templateId;
            me.instanceId = wfcore.instanceId;
            isReload = true;
            me.ShowCurrent();
        },

        ReDraw: function () {
            this.InitialForm();
            this.DrawPic();
        },


        CanCallBack: function (workItem) {
            var me = this;
            if (me.operate > 1)
                return true;
            var handler = workItem.workitemHandlers.where(me.UserID, 'HANDLE_USER_ID');
            if (handler != undefined && handler.handleResult == HandleResult.Adopt) {
                return true;
            }
            return false;

        },

        IsInPath: function (activity, targetActivityId) {

            var me = this;
            if (activity == undefined || activity == null || activity.activityType == ActivityType.Start)
                return false;
            if (activity.activityId == targetActivityId)
                return true;
            else {
                var flag = false;
                $.each(me.effectRules, function (x, rule) {
                    if (rule.toActivityId == activity.activityId) {
                        $.each(me.effectWorkItems, function (y, workItem) {
                            if (workItem.activityId == rule.fromActivityId) {
                                flag = flag || me.IsInPath(me.Template.activities.where(workItem.activityId, 'activityId'), targetActivityId);
                            }
                        })
                    }
                });
                return flag;
            }
        },


        BindMenu: function (div, result) {
            var me = this;
            div.contextMenu('adjustMenu',
                {
                    bindings: {

                        'adjust': function (t, target) {
                            me.Adjust(result.workItem);
                        },
                        'approveproxy': function (t, target) {
                            me.approveproxy(result);
                        },

                        onShowMenu: function (e, menu) {
                            return menu;
                        }
                    }
                });

        },

        Adjust: function (workItem) {
            var me = this;
            var result = $.AjaxRequest(initialData('Workflow_Participant_GetActivityParticipant', $.toJSON({
                "activityId": workItem.activityId,
                "ORG_ID": me.Instance.ORG_ID,
                "instanceId": me.Instance.instanceId
            })));
            if (result.success) {
                var userList = result.data;
                $.each(userList, function (i, val) {
                    val.nocheck = false;
                })
                //初始化ztree
                zTreeObj = $.fn.zTree.init($("#treeOrg"), WorkflowMoinitor.Setting, userList);
                zTreeObj.expandAll(true);
                //反绑
                $.each(workItem.workitemHandlers, function (k, val) {
                    var node = zTreeObj.getNodeByParam('ID', val.USER_ID, null);
                    if (node != undefined && node != null)
                        zTreeObj.checkNode(node, true, true);
                });
                //弹出窗口

                var layerNum = me.PopWindow($("#divOrg"), $("#divorgTitle"), '360px', '420px');
                //绑定事件
                $("#btnCreateOK").unbind();
                $("#btnCreateCancel").unbind();
                //提交
                $("#btnCreateOK").click(function () {
                    var nodes = zTreeObj.getCheckedNodes();

                    if (nodes.length > 0) {
                        var users = me.InitialUser(nodes);
                        if (users.length == 0) {
                            alert('请选择处理人');
                        }
                        else {
                            var result = $.AjaxRequest(initialData('Workflow_Adjust', $.toJSON({
                                "WORKITEM_ID": workItem.WORKITEM_ID,
                                "HANDLE_USER": users
                            })));
                            if (result.success) {
                                alert('调整成功');
                                window.location.reload();
                            }
                            else alert('调整失败');
                        }
                    }
                });
                $("#btnCreateCancel").click(function () {
                    layer.close(layerNum);
                });
            }
        },

        approveproxy: function (result) {
            var me = this;
            //清空容器

            $("#divUserTitle").html("<span>当前步骤:" + result.workItem.WORKITEM_NAME + " </span>")
            me.postActivityCollection = [];
            me.nextActivityCollection = [];

            me.postActivityCollection = $.AjaxRequest(initialData('Workflow_GetNextActivity', $.toJSON({
                "activityId": result.workItem.activityId,
                "RULE": null
            }))).data;
            if (me.postActivityCollection != null) {
                me.nextActivityCollection = new Array();
                $.each(me.postActivityCollection, function (i, postActivity) {
                    if (postActivity.ACTIVITY.activityType != 3 && postActivity.ACTIVITY.activityType != 6) {
                        me.nextActivityCollection[me.nextActivityCollection.length] = (postActivity);
                    }
                });

                if (me.nextActivityCollection.length == 1 && (me.nextActivityCollection[0].ACTIVITY.activityType == ActivityType.End || me.nextActivityCollection[0].ACTIVITY.activityType == ActivityType.Merging)) {

                    me.nextParticipaints = [{ACTIVITY: me.nextActivityCollection[0].ACTIVITY}];
                    me.submit(result.workItem, HandleResult.Adopt);
                }
                else {
                    var myWindow = me.InitailUserWindow();
                    var layerNum = me.PopWindow($("#divUserContainer"), $("#divUserTitle"), new String(myWindow.width + 20) + 'px', new String(myWindow.height + 20) + 'px');
                    //绑定事件
                    me.BindSubmitBtn(myWindow.submitData, result, layerNum, HandleResult.Adopt);
                }
            }

        },

        BindSubmitBtn: function (submitData, result, layerNum) {
            var me = this;
            $("#btnSubmit").unbind();
            $("#btnSubmitCancel").unbind();
            $("#btnSubmitCancel").click(function () {
                layer.close(layerNum);
            });
            $("#btnSubmit").click(function () {
                if (me.validate(submitData).result) {
                    me.GetsubmitData(submitData, result.workItem.activityId);
                    me.submit(result.workItem, HandleResult.Adopt);
                    layer.close(layerNum);
                }
                else alert("请选择处理人");
            });

        },


        InitailUserWindow: function () {

            var me = this;
            var col = 3;
            $("#divUser").html('');
            var width = me.nextActivityCollection.length * 250;
            if (width >= 250 * col)
                width = 250 * col;
            var height = me.nextActivityCollection.length % col == 0 ? 250 * me.nextActivityCollection.length / col : ((me.nextActivityCollection.length - me.nextActivityCollection.length % col) / col + 1) * 250;
            $("#divUserContainer").css("width", new String(width + 20) + "px");
            $("#divUser").css({"height": new String(height + 20) + 'px', "width": '100%'});
            var id = 0;

            var submitData = new Array();
            //根据后继步骤，填充表单
            $.each(me.nextActivityCollection, function (i, val) {//class="messageboxContent"
                var divContainer = $("<div style='float:left; width:243px; margin:3px;' class='messageboxContent'>");
                var divTitle = $("<div style='width:100%; margin:0px; padding:0px; height:22px; line-height:22px; background-color:#99bce8;'>");
                var divContent = $("<div style='width:238px; height:230px; overflow:auto;'>");
                divContainer.append(divTitle);
                divContainer.append(divContent);
                $("#divUser").append(divContainer);

                var input = $("<input type='checkbox' checked style='margin-left:5px; margin-right:2px; margin-top:2px;'>");
                divTitle.append(input);
                var span = $("<span>" + val.ACTIVITY.activityName + "</span>");
                divTitle.append(span);
                var userList = $.AjaxRequest(initialData('Workflow_Participant_GetActivityParticipant', $.toJSON({
                    "ORG_ID": me.Instance.ORG_ID,
                    "instanceId": me.Instance.instanceId,
                    "activityId": val.ACTIVITY.activityId
                }))).data;

                var nodes = userList;
                var ul = $("<ul id=" + new String(++id) + ">").attr("class", "ztree").css("width", "auto");
                var myZtree = $.fn.zTree.init(ul, WorkflowMoinitor.Setting, nodes);
                myZtree.expandAll(true);
                divContent.append(ul);

                input.click(function (e) {
                    var nodes = myZtree.transformToArray(myZtree.getNodes());
                    if (!input.is(":checked")) {
                        $.each(nodes, function (l, node) {
                            myZtree.checkNode(node, false, true);
                            myZtree.setChkDisabled(node, true);
                        })
                    }
                    else {
                        $.each(nodes, function (l, node) {
                            myZtree.setChkDisabled(node, false);
                        })
                    }
                });

                submitData[submitData.length] = {
                    'Input': input,
                    'Tree': myZtree,
                    'Activity': val
                };
            });
            return {
                'submitData': submitData,
                'height': height,
                'width': width
            };

        },


        PopWindow: function (div, title, width, height, type, close) {
            if (type == undefined) type = 1;
            if (close == undefined) close = true;
            var layerNum = $.layer({
                type: type,
                title: false,
                move: [title, true],
                fix: false,
                closeBtn: close,
                shadeClose: false,
                shade: [0.5, '#000', true],
                border: [5, 0.3, '#666', true],
                offset: ['50%', '50%'],
                area: [width, height],
                page: {dom: div},
                success: function () {
                }
            });
            $(".xubox_main").css("background-color", "transparent");
            return layerNum;
        },
        nextParticipaints: [],

        validate: function (submitDatas) {
            var result = {
                result: true,
                message: ''
            }
            $.each(submitDatas, function (i, submitData) {
                if (submitData.Input.is(":checked")) {
                    if (submitData.Activity.ACTIVITY.activityType == ActivityType.End || submitData.Activity.ACTIVITY.activityType == ActivityType.Merging) {
                    }
                    else {
                        var nodes = submitData.Tree.getCheckedNodes();
                        if (nodes.length == 0) {
                            result.result = false;
                        }
                    }
                }

            });
            return result;
        },


        GetsubmitData: function (submitDatas, activityId) {

            var me = this;


            if (!confirm("确定提交吗？")) {
                return;
            }

            me.nextParticipaints = new Array();
            $.each(submitDatas, function (i, submitData) {
                if (submitData.Input.is(":checked")) {
                    $.each(me.postActivityCollection, function (j, postActivity) {
                        if (postActivity.ACTIVITY.activityId == submitData.Activity.ACTIVITY.activityId) {
                            submitData.ACTIVITY = postActivity.ACTIVITY;
                            submitData.PARENT_ACTIVITY = postActivity.PARENT_ACTIVITY
                        }
                    });
                    me.dealNextParticipaints(submitData.PARENT_ACTIVITY, me.postActivityCollection, activityId);
                    //如果被选中

                    var nodes = submitData.Tree.getCheckedNodes();
                    var users = new Array();
                    if (nodes.length > 0) {
                        users = me.InitialUser(nodes);
                    }

                    me.nextParticipaints[me.nextParticipaints.length] = {
                        ACTIVITY: submitData.ACTIVITY,
                        USER_IDS: users,
                        PARENT_ACTIVITY: submitData.PARENT_ACTIVITY
                    }
                }
            });
            me.nextParticipaints = submitDatas.length == 0 ? null : me.nextParticipaints;


        },

        submit: function (workItem, handleResult, userId) {

            var me = this;
            var submitData = {
                WORKITEM_ID: workItem.WORKITEM_ID,
                instanceId: me.Instance.instanceId,
                handleResult: handleResult,
                HANLE_SUGGESTION: '',
                USER_ID: {
                    CURRENT_USER_ID: me.UserID,
                    CURRENT_USER_NAME: $.Request.QueryString("UserName"),
                    PROXY_USER_ID: userId == undefined ? workItem.workitemHandlers[0].USER_ID : me.UserID,
                    PROXY_USER_NAME: userId == undefined ? workItem.workitemHandlers[0].USER_NAME : $.Request.QueryString("UserName")
                },
                rule: null,
                NEXT_ACTIVITY: me.nextParticipaints
            };

            if (!$.AjaxRequest(initialData('Workflow_Submit', $.toJSON(submitData))).success) alert("操作失败");
            else {
                alert("调整成功");
                divPic.html('');
                me.GetInstanceById();
                me.DrawPic();

                //window.location.reload();
            }

        },

        dealNextParticipaints: function (activity, activityId) {
            var me = this;
            if (activity == null) return;
            if (activity.activityId == activityId) return;
            if (activity.activityType != 3 && activity.activityType != 6) return;
            $.each(me.postActivityCollection, function (i, postActivity) {
                if (postActivity.ACTIVITY.activityId == activity.activityId && !me.isContainActivity(activity.activityId))
                    me.nextParticipaints[me.nextParticipaints.length] = postActivity;
                me.dealNextParticipaints(postActivity.PARENT_ACTIVITY.activityId)
            });
        },

        isContainActivity: function (activityId) {
            var me = this;
            var flag = false;
            $.each(me.nextParticipaints, function (p, nextParticipaint) {
                if (nextParticipaint.ACTIVITY.activityId == activityId) flag = true;
            });
            return flag;
        },

        InitialUser: function (nodes) {
            var users = new Array();
            $.each(nodes, function (k, val) {
                if (val.children == undefined || val.children.length == 0) {
                    var user = {};
                    user.CURRENT_USER_ID = val.ID;
                    user.CURRENT_USER_NAME = val.NAME;
                    user.PROXY_USER_ID = val.ID;
                    user.PROXY_USER_NAME = val.NAME;
                    users[users.length] = user;
                }
            });
            return users;
        },

        cloneObject: function cloneObject(obj) {
            if (obj === null) {
                return null;
            }
            var o = obj.constructor === Array ? [] : {};
            for (var i in obj) {
                if (obj.hasOwnProperty(i)) {
                    o[i] = typeof obj[i] === "object" ? cloneObject(obj[i]) : obj[i];
                }
            }
            return o;
        },


        AddRule: function (rule) {
            rule.Position = [];
            if (rule.ruleType == 0 && rule.isDel == 0) {
                var color = legend[3].color;
                var me = this;
                $.each(me.handledRule, function (hr, val) {
                    if (val == rule.RULE_ID) {
                        color = legend[4].color;
                        return false;
                    }
                });

                rule.color = color;
                var position = rule.coordinate.split(',');
                var positionX = position[0].split('$');
                var positionY = position[1].split('$');

                for (i = 0; i < positionX.length; i++) {
                    positionX[i] *= me.proportion;
                    positionY[i] *= me.proportion;
                }


                if (positionX.length > 2)
                    for (j = 1; j < positionX.length; j++) {
                        var startPoint = new Point(positionX[j - 1], positionY[j - 1]);
                        var endPoint = new Point(positionX[j], positionY[j]);
                        if (j == 1) {
                            var activity = me.Template.activities.where(rule.fromActivityId, 'id');
                            startPoint = me.GetIntersectionPoint(activity.activityType, activity.Position, endPoint);
                            rule.Position.push(startPoint);
                        }
                        if (j == positionX.length - 1) {
                            var activity = me.Template.activities.where(rule.toActivityId, 'id');
                            endPoint = me.GetIntersectionPoint(activity.activityType, activity.Position, startPoint);

                        }
                        rule.Position.push(endPoint);
                        if (startPoint.Y > me.maxHeigth) me.maxHeigth = startPoint.Y;
                        if (endPoint.Y > me.maxHeigth) me.maxHeigth = endPoint.Y;

                        if (startPoint.X > me.maxWidth) me.maxWidth = startPoint.X;
                        if (endPoint.X > me.maxWidth) me.maxWidth = endPoint.X;


                        me.DrawLine(startPoint, endPoint, color, '');
                    }
                else if (positionX.length == 2) {
                    var activityF = me.Template.activities.where(rule.fromActivityId, 'id');
                    var activityT = me.Template.activities.where(rule.toActivityId, 'id');
                    var positionF = activityF.Position;
                    var positionT = activityT.Position;
                    startPoint = me.GetIntersectionPoint(activityF.activityType, positionF, positionT);
                    endPoint = me.GetIntersectionPoint(activityT.activityType, positionT, startPoint);
                    me.DrawLine(startPoint, endPoint, color, '');

                    if (startPoint.Y > me.maxHeigth) me.maxHeigth = startPoint.Y;
                    if (endPoint.Y > me.maxHeigth) me.maxHeigth = endPoint.Y;

                    if (startPoint.X > me.maxWidth) me.maxWidth = startPoint.X;
                    if (endPoint.X > me.maxWidth) me.maxWidth = endPoint.X;

                    rule.Position.push(startPoint);
                    rule.Position.push(endPoint);
                }


                //me.DrawLine(startPoint, endPoint, color, '');
                //me.DrawLine(arrow.upArrow, endPoint, color, '');
                //me.DrawLine(arrow.downArrow, endPoint, color, '');
            }
        },

        GetActivityStatus: function (activityId) {
            var me = this;
            var result = {
                status: -1,
                workItem: null
            }

            var status = -1;
            if (me.Instance.workitems)
                $.each(me.Instance.workitems, function (m, workItem) {
                    if (workItem.activityId == activityId &&
                        workItem.isDel == 0 &&
                        workItem.handleResult != HandleResult.Retrieve &&
                        workItem.handleResult != HandleResult.Return &&
                        (workItem.handleResult == HandleResult.Adopt || workItem.handleResult == HandleResult.None || workItem.handleResult == HandleResult.Transfer)) {
                        result.status = workItem.handleResult == HandleResult.Adopt ? 1 : 0;
                        result.workItem = workItem;
                        return false;
                    }
                })
            return result;


        },

        GetHandler: function (workItem) {
            var me = this;
            var info = {
                handlers: '',
                title: ''
            }

            if (workItem.handleResult == HandleResult.Adopt) {
                var i = 0;

                $.each(workItem.workitemHandlers, function (h, handler) {
                    if ((handler.handleResult == HandleResult.Adopt || handler.handleResult == HandleResult.Transfer) && handler.isDel == 0) {
                        if (i > 0) {
                            info.handlers += ",";
                            info.title += "\r\n--------------------";
                        }
                        ++i;
                        info.handlers += handler.handleUserName;
                        info.title += "处 理 人：" + handler.handleUserName + "\r\n" + "处理时间：" + moment(handler.finishTime, 'YYYY-MM-DD HH:MM:SS');
                        if (handler.handleSuggestion)
                            info.title += "\r\n审批意见：" + handler.handleSuggestion;
                    }
                })
            }
            else {
                var i = 0;
                $.each(workItem.workitemHandlers, function (h, handler) {
                    if (i > 0)
                        info.handlers += ",";
                    ++i;
                    info.handlers += handler.userName;
                })
                info.title = info.handlers;
            }
            //if (handlers.Length > 0)
            //    handlers = handlers.substring(0, handlers.length - 1);
            return info;
        },

        DrawRule: function (rule) {
            var me = this;
            for (i = 1; i < rule.Position.length; i++) {
                me.DrawLine(rule.Position[i - 1], rule.Position[i], rule.color);
                if (i == rule.Position.length - 1) {
                    var arrow = me.mathHelper.Arrow(rule.Position[i - 1], rule.Position[i], 25);
                    me.DrawLine(arrow.upArrow, rule.Position[i], rule.color, '');
                    me.DrawLine(arrow.downArrow, rule.Position[i], rule.color, '');
                }
            }

        },

        DrawLine: function (p1, p2, color, title) {
            var me = this, angle = getAngle();


            var x0 = p1.X, y0 = p1.Y, x1 = p2.X, y1 = p2.Y,
                height = 3;


            me.draw(
                function () {
                    var grad = getEnd();
                    var lx = x1 - x0;
                    var ly = y1 - y0;
                    var l = Math.sqrt(lx * lx + ly * ly);
                    cxt.beginPath();
                    var gradient = cxt.createLinearGradient(grad.x0, grad.y0, grad.x1, grad.y1);
                    if (color == 'red') {
                        gradient.addColorStop("0", "green");
                        gradient.addColorStop("0.5", "blue");
                        gradient.addColorStop("1.0", "red");
                    }
                    else {
                        gradient.addColorStop("0", "green");
                        gradient.addColorStop("0.5", "blue");
                        gradient.addColorStop("1.0", "red");
                    }

                    cxt.fillStyle = cxt.strokeStyle = color;


                    cxt.moveTo(x0, y0);
                    cxt.lineTo(x1, y1);

                    cxt.lineWidth = height;
                    //cxt.fill();
                    cxt.stroke();

                }
            )


            function getAngle() {
                var angle;

                var sincos = mathHelper.Angle(p1, p2);
                //0~180
                if (sincos.sin > 0) {
                    angle = Math.acos(sincos.cos);
                }
                //180~360
                else if (sincos.sin < 0) {
                    angle = 2 * Math.PI - Math.acos(sincos.cos);
                }
                else {
                    if (sincos.cos == 1) angle = 0;
                    else if (sincos.cos == -1) angle = Math.PI;
                }
                return angle;
            }

            function getEnd() {
                return {
                    x0: p1.X + height * Math.cos(angle - Math.PI / 2) / 2,
                    y0: p1.Y + height * Math.sin(angle - Math.PI / 2) / 2,
                    x1: p1.X + height * Math.cos(angle + Math.PI / 2) / 2,
                    y1: p1.Y + height * Math.sin(angle + Math.PI / 2) / 2
                };
            }

        },

        draw: function (handler) {
            cxt.save();
            try {
                if (handler) {
                    handler(cxt);
                }
            } catch (e) {

            }
            cxt.restore();
        },

        rotate: function (obj, angle) {
            var rotate = "rotate(" + angle + "deg)";
            obj.css({
                'transform-origin': '0 0',
                'transform': rotate,
                '-ms-transform': rotate, /* IE 9 */
                '-moz-transform': rotate, /* Firefox */
                '-webkit-transform': rotate, /* Safari 和 Chrome */
                '-o-transform': rotate    /* Opera */
            })
        },

        GetIntersectionPoint: function (activityType, position, point) {
            var me = this;
            if (activityType == ActivityType.Start || activityType == ActivityType.End || activityType == ActivityType.Freedom) {
                var r;
                if (activityType == ActivityType.Start || activityType == ActivityType.Freedom) {
                    r = StyleDefine.Activity.Start.Radius;
                }
                else if (activityType == ActivityType.End) {
                    r = StyleDefine.Activity.End.Radius;
                }

                point = new Point(point.X - position.X, point.Y - position.Y);
                var dis = me.mathHelper.PointDistinct(point.X, point.Y, 0, 0);

                var sin = point.X / dis;
                var cos = point.Y / dis;

                var resultX = r * sin + position.X;
                var resultY = r * cos + position.Y;
                return new Point(resultX, resultY);


            }

            else if (activityType == ActivityType.Condition || activityType == ActivityType.Merging || activityType == ActivityType.Branching) {
                var p1;
                var p2;

                var width;
                var height;

                if (activityType == ActivityType.Condition) {
                    width = StyleDefine.Activity.Condition.diamondWidth;
                    height = StyleDefine.Activity.Condition.diamondHeight;
                }
                else if (activityType == ActivityType.Merging) {
                    width = StyleDefine.Activity.Merging.diamondWidth;
                    height = StyleDefine.Activity.Merging.diamondHeight;
                }
                else if (activityType == ActivityType.Branching) {
                    width = StyleDefine.Activity.Branching.diamondWidth;
                    height = StyleDefine.Activity.Branching.diamondHeight;
                }


                if (point.X > position.X) {
                    //右侧偏下
                    if (point.Y > position.Y) {
                        p1 = new Point(0, height);
                        p2 = new Point(width, 0);
                    }
                    else if (point.Y == position.Y) {
                        return new Point(position.X + width, position.Y)

                    }
                    //右侧偏上
                    else {
                        p1 = new Point(0, -height);
                        p2 = new Point(width, 0);

                    }
                }
                else if (point.X == position.X) {
                    if (point.Y > position.Y)
                        return new Point(position.X, position.Y + height);
                    else return new Point(position.X, position.Y - height);
                }
                else {
                    //左侧偏上
                    if (point.Y > position.Y) {
                        p1 = new Point(-width, 0);
                        p2 = new Point(0, height);
                    }
                    else if (point.Y == position.Y) {
                        return new Point(position.X - width, position.Y);
                    }

                    else {
                        p1 = new Point(-width, 0),
                            p2 = new Point(0, -height)
                    }
                }

                return me.mathHelper.GetIntersectionPoint(position, point, p1, p2);

            }

            else {

                var activityRectVertexY;
                var activityRectVertexX;
                var r = 0;
                if (activityType == ActivityType.Drafting) {
                    activityRectVertexY = StyleDefine.Activity.Drafting.activityRectVertexY;
                    activityRectVertexX = StyleDefine.Activity.Drafting.activityRectVertexX;
                    //  r = StyleDefine.Activity.Drafting.activityRectAngle;
                }
                else if (activityType == ActivityType.Approval) {
                    activityRectVertexY = StyleDefine.Activity.Approval.activityRectVertexY;
                    activityRectVertexX = StyleDefine.Activity.Approval.activityRectVertexX;
                    //  r = StyleDefine.Activity.Approval.activityRectAngle;
                }
                //以当前顶点为坐标系
                var relativeCoordinates = new Point(point.X - position.X, point.Y - position.Y);
                var me = this;
                var k = 0;

                if (relativeCoordinates.X != 0) {
                    k = relativeCoordinates.Y / relativeCoordinates.X;
                }
                //鼠标在节点的右侧
                if (relativeCoordinates.X > 0) {
                    //                    activityRectVertexX
                    //                    activityRectVertexY
                    //右侧偏下
                    if (relativeCoordinates.Y > 0) {
                        var y1 = activityRectVertexY;
                        var x1 = y1 / k;
                        var result = new Point(x1, y1);
                        var center = new Point(activityRectVertexX - r, activityRectVertexY - r);
                        if (x1 > activityRectVertexX) {
                            //在弧上
                            result.X = activityRectVertexX;
                            result.Y = k * result.X;
                        }
                        if (result.X > center.X && result.Y > center.Y) {

                            var tmp = me.mathHelper.LineCircleIntersection(center, r, k, relativeCoordinates);
                            if (tmp != null)
                                result = tmp;
                        }
                        return result.MovePoint(position);

                    }

                    else if (relativeCoordinates.Y == 0) {
                        return new Point(position.X + activityRectVertexX, position.Y);
                    }
                    //右侧偏上
                    else {
                        var y1 = -activityRectVertexY;

                        var x1 = y1 / k;

                        var result = new Point(x1, y1);

                        var center = new Point(activityRectVertexX - r, -activityRectVertexY + r);

                        if (result.X > center.X) {
                            result.X = activityRectVertexX;
                            result.Y = k * result.X;
                        }

                        if (result.X > center.X && result.Y < center.Y) {
                            var tmp = me.mathHelper.LineCircleIntersection(center, r, k, relativeCoordinates);
                            if (tmp != null)
                                result = tmp;
                        }

                        return result.MovePoint(position);
                    }
                }
                else if (relativeCoordinates.X == 0) {
                    if (relativeCoordinates.Y > 0) {
                        return new Point(position.X, position.Y + activityRectVertexY);
                    }
                    else {
                        return new Point(position.X, position.Y - activityRectVertexY);
                    }

                }
                else {
                    //左侧偏上
                    if (relativeCoordinates.Y > 0) {
                        var y1 = activityRectVertexY;
                        var x1 = y1 / k;
                        var result = new Point(x1, y1);
                        var center = new Point(-activityRectVertexX + r, activityRectVertexY - r);
                        if (x1 < -activityRectVertexX) {
                            result.X = -activityRectVertexX;
                            result.Y = k * result.X;
                        }

                        if (result.X < center.X && result.Y > center.Y) {

                            var tmp = me.mathHelper.LineCircleIntersection(center, r, k, relativeCoordinates);
                            if (tmp != null)
                                result = tmp;
                        }
                        return result.MovePoint(position);
                    }
                    else if (relativeCoordinates.Y == 0) {
                        return new Point(position.X - activityRectVertexX, position.Y);
                    }

                    else {
                        var y1 = -activityRectVertexY;
                        var x1 = y1 / k;
                        var result = new Point(x1, y1);
                        var center = new Point(-activityRectVertexX + r, -activityRectVertexY + r);
                        if (x1 < -activityRectVertexX) {
                            if (x1 < -activityRectVertexX + r) {
                                result.X = -activityRectVertexX;
                                result.Y = k * result.X;
                            }
                        }
                        if (result.X < center.X && result.Y < center.Y) {
                            var tmp = me.mathHelper.LineCircleIntersection(center, r, k, relativeCoordinates);
                            if (tmp != null) result = tmp;
                        }
                        return result.MovePoint(position);
                    }
                }
            }

        },

        handledRule: new Array(),

        GetHandledRuleInvoke: function () {
            var me = this;
            me.handledRule = new Array();
            //根据有效工作项查找到的使用过的规则
            $.each(me.effectWorkItems, function (a, val) {
                var item = me.EffectPreWorkItem(val);
                if (item != undefined) {
                    var ruleId = me.GetRuleIdByActivity(item.activityId, val.activityId);
                    if (ruleId != null && !me.IsHaveRule(ruleId))
                        me.handledRule[me.handledRule.length] = ruleId;
                }
            });

            $.each(me.Template.activities, function (i, activity) {
                if (activity.activityType == ActivityType.Merging) {
                    $.each(me.effectRules, function (j, rule) {
                        if (rule.toActivityId == activity.activityId) {
                            var fromItem = me.effectWorkItems.where(rule.fromActivityId, 'activityId');
                            if (fromItem != undefined && fromItem.handleResult == HandleResult.Adopt) {
                                var ruleId = rule.RULE_ID;
                                if (ruleId != null && !me.IsHaveRule(ruleId))
                                    me.handledRule[me.handledRule.length] = ruleId;
                            }
                        }
                    })
                }
            });


            var start = me.Template.activities.where(ActivityType.Start, 'activityType');

            var firstRule = me.effectRules.where(start.id, 'fromActivityId');
            var ruleId = firstRule.RULE_ID;
            if (ruleId != null && !me.IsHaveRule(ruleId))
                me.handledRule[me.handledRule.length] = ruleId;


        },

        GetActivityByActivityType: function (activityType) {
            var tmp = null;
            var me = this;
            $.each(me.Template.activities, function (as, val) {
                if (val.isDel == 0 && val.activityType == activityType) {
                    tmp = val;
                    return false;
                }
            });
            return tmp;
        },
        ShowCurrent: function () {
            var me = this;

            setInterval = window.setInterval(function () {
                if (!isReload || submitFlag < 4) {
                    ++submitFlag
                    if (current) {
                        if (submitFlag % 2 == 0) {
                            current.css({"border": "1px solid #555", "box-shadow": "#777 0px 0px 3px 3px"});
                        } else {
                            current.css({"border": "3px solid #555", "box-shadow": "#777 0px 0px 8px 8px"});
                        }
                    }
                } else {

                    $.request("/workflow/instance/find", {id: me.instanceId}, function (data) {
                        me.Instance = data;
                    }, false, false);
                    me.InitialForm();
                    me.DrawPic();
                    isReload = false;
                    wfcore.    WaitClose();
                }
            }, 500);
            return setInterval;

        },

        EffectPreWorkItem: function (workItem) {
            var me = this;
            var preWorkItem = me.Instance.workitems.where(workItem.parentId, 'id');
            if (preWorkItem == undefined)
                return null;
            var effectworkitem = me.effectWorkItems.where(preWorkItem.id, 'id');
            if (effectworkitem != undefined && effectworkitem != null) {
                return effectworkitem;
            }
            else return me.EffectPreWorkItem(preWorkItem);
        },


        GetWorkItemByActivityId: function (activityId) {
            var me = this;
            var result = new Array();
            $.each(me.effectWorkItems, function (item, val) {
                if (val.activityId == activityId)
                    result[result.length] = val;

            });
            return result;


        },

        GetRulesByFromActivityId: function (fromACid) {
            var me = this;
            var result = new Array();
            $.each(me.Template.rules, function (t, val) {
                if (val.isDel == 0 && val.fromActivityId == fromACid && val.ruleType == 0) {
                    result[result.length] = val;
                }
            });
            return result;
        },


        GetRulesByToActivityId: function (fromACid) {
            var me = this;
            var result = new Array();
            $.each(me.Template.rules, function (t, val) {
                if (val.isDel == 0 && val.fromActivityId == fromACid && val.ruleType == 0) {
                    result[result.length] == val;
                }
            });

        },

        GetRuleIdByActivity: function (fromActivity, toActivity) {
            var me = this;
            var result = null;

            $.each(me.Template.rules, function (t, val) {
                if (val.isDel == 0 && val.fromActivityId == fromActivity && val.ruleType == 0 && val.toActivityId == toActivity) {
                    result = val;
                    return false;
                }
            });
            if (result != null)
                return result.RULE_ID;
            return null;

        },

        IsHaveRule: function (ruleId) {
            var ishave = false;
            var me = this;
            $.each(me.handledRule, function (i, val) {
                if (val == ruleId) {
                    ishave = true;
                    return false;
                }
            })
            return ishave;

        },


        ShowHistory: function (data) {
            var me = this;
            var divHistory = $("#divHistory");
            //输出结果
            divHistory.html('');
            var items = data.sort(function (a, b) {
                var aDate = new Date(a.CREATETIME);
                var bDate = new Date(b.CREATETIME);
                return aDate - bDate;
            });

            var div = $("<div class='divcontainer '>").html(wfcore.History(data));
            divHistory.append(div);
            var height = div.height();
            $("#divHistroyContainer").modal();
        },

        IsShowProp: false,

        Setting: {
            view: {
                dblClickExpand: false,
                showLine: true
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "ID",
                    pIdKey: "PARENT_ID",
                    rootPId: null
                },
                key: {
                    name: "NAME"
                }
            },
            check: {
                enable: true,
                chkDisabledInherit: true

            }


        }


    }


    $.fn.monitor = function (parm) {

        wfcore = parm;
        $this = $(this);

        var worklow = new WorkflowMoinitor(this, wfcore);
        parm.monitor = worklow;
        worklow.InitialForm();
        worklow.DrawPic();
    }

})(jQuery);

